package com.base.timer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.base.po.coupon_new.CouponGoodsNew;
import com.base.po.coupon_new.GoodsTypeResponseData;
import com.base.po.coupon_sdk.CouponInfoUtilNew;
import com.base.po.param.NetState;
import com.base.po.voip_coupon.CouponBrand;
import com.base.po.voip_coupon.CouponCategory;
import com.base.service.COUPON.CouponBrandService;
import com.base.service.COUPON.CouponCategoryService;
import com.base.service.COUPON.CouponGoodsNewService;
import com.base.utils.DateUtil;
import com.base.utils.Produce;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.List;

@Log4j
@Component
@RequestMapping("/updateResource")
public class haiweiTimer {
    private final CouponCategoryService couponCategoryService;
    private final CouponBrandService couponBrandService;
    private final CouponGoodsNewService couponGoodsNewService;


    @Autowired
    public haiweiTimer(CouponGoodsNewService couponGoodsNewService, CouponCategoryService couponCategoryService, CouponBrandService couponBrandService) {
        this.couponGoodsNewService = couponGoodsNewService;
        this.couponCategoryService = couponCategoryService;
        this.couponBrandService = couponBrandService;
    }

    //手动更新数据接口
    @RequestMapping(value = "/HaiWei", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState index(HttpServletRequest request) throws Exception {
        log.warn("[海威手动] 开始更新商品数据");
        //执行读取油站的定时任务
        try {
            log.warn("清空表数据 couponBrand");
            couponBrandService.clearAll();
            log.warn("清空完毕 couponBrand");
            log.warn("清空表数据 couponCategory");
            couponCategoryService.clearAll();
            log.warn("清空完毕 couponCategory");
            getBrands(null);
        } catch (Exception e) {
            log.warn("[海威手动] 获取品牌报错"+e);
            e.printStackTrace();
        }
        try {
            getGoods(null,null);
        } catch (UnsupportedEncodingException e) {
            log.warn("[海威手动] 更新商品报错"+e);
            e.printStackTrace();
        }
        log.warn("[海威手动] 结束更新");
        return new NetState(NetState.SUCCESS_CONN,"success");
    }
    // 365优惠券更新商品信息（定时器用）
    public NetState getGoods( String brandid, String commoditId) throws UnsupportedEncodingException {
        String resultData = CouponInfoUtilNew.goodsGet(brandid, commoditId);
        JSONArray jsonArray = JSONArray.parseArray(resultData);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject item = jsonArray.getJSONObject(i);
            CouponGoodsNew couponGoodsNew = new CouponGoodsNew(item.getString("img_url"), new BigDecimal(item.getString("sell_price")), item.getString("goods_no"),
                    DateUtil.strToDate2(item.getString("expiration_time")), item.getString("guarantee_period"), item.getString("name"), item.getString("brand_name"),
                    item.getString("goods_type"), new BigDecimal(item.getString("official_price")), item.getString("sell_status"), item.getString("brand_id"), item.getString("use_explain"));

            CouponGoodsNew cGOld = couponGoodsNewService.selectCouponGoodsNewByGoodsNo(item.getString("goods_no"));

            if (cGOld != null) {
                couponGoodsNew.setId(cGOld.getId());
                couponGoodsNewService.updateByPrimaryKeySelective(couponGoodsNew);
                log.warn("[365券] 更新一条数据");
            } else {
                couponGoodsNewService.insertSelective(couponGoodsNew);
                log.warn("[365券] 插入一条数据");

            }

        }
        return new NetState("success", NetState.SUCCESS_CONN, jsonArray);
    }


    // 365优惠券获取品牌信息 定时器（非接口）
    public NetState getBrands( String parentid) throws Exception {
        NetState netState = new NetState();
        List<GoodsTypeResponseData> responseDatas = CouponInfoUtilNew.goodsType();
        if (responseDatas != null) {
            for (int i = 0; i < responseDatas.size(); i++) {
                GoodsTypeResponseData responseData = responseDatas.get(i);
                CouponCategory category = couponCategoryService.selectByCategory(responseData.getCategory());
                if (category == null) {
                    category = new CouponCategory();
                    category.setCategory(responseData.getCategory());
                    category.setId(Produce.getUUID()); // 设置参数 主键ID
                    category.setParentid(parentid); // 代理商ID
                    category.setDatastatus((byte) 1); // 数据状态
                    couponCategoryService.insertSelective(category);
                }

                CouponBrand brand = couponBrandService.selectByPrimaryKey(String.valueOf(responseData.getBrand_id()));
                if (brand != null) {
                    brand.setId(String.valueOf(responseData.getBrand_id()));
                    brand.setParentid(parentid);
                    brand.setTopid(category.getId());
                    brand.setCategory(responseData.getBrand_name());
                    brand.setPic(responseData.getBrand_logo());
                    brand.setDatastatus((byte) responseData.getSell_status());
                    couponBrandService.updateByPrimaryKeySelective(brand);
                } else {
                    brand = new CouponBrand();
                    brand.setId(String.valueOf(responseData.getBrand_id()));
                    brand.setParentid(parentid);
                    brand.setTopid(category.getId());
                    brand.setCategory(responseData.getBrand_name());
                    brand.setPic(responseData.getBrand_logo());
                    brand.setDatastatus((byte) responseData.getSell_status());
                    couponBrandService.insertSelective(brand);
                }
            }
        }

        netState.setErrorCode(NetState.SUCCESS_CONN);
        netState.setData("查询成功");
        return netState;
    }

    @Scheduled(cron = "0 0 0,13,18,21 * * ?")
    public void updateShopGoods() {
        log.warn("[海威定时任务] 开始更新商品数据");
        //执行读取油站的定时任务
        try {
            log.warn("清空表数据 couponBrand");
            couponBrandService.clearAll();
            couponCategoryService.clearAll();
            log.warn("清空完毕 couponBrand");
            getBrands(null);
        } catch (Exception e) {
            log.warn("[海威自动] 获取品牌报错"+e);
            e.printStackTrace();
        }
        try {
            log.warn("清空表数据 couponCategory");

            log.warn("清空完毕 couponCategory");
            getGoods(null,null);
        } catch (UnsupportedEncodingException e) {
            log.warn("[海威自动] 更新商品报错"+e);
            e.printStackTrace();
        }
        log.warn("[海威自动] 结束更新");

    }
}
